package ca.llsutherland.nfl.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.nfl.domain.Season;
import ca.llsutherland.nfl.exception.ValidationException;
import ca.llsutherland.nfl.helper.SeasonHelper;
import ca.llsutherland.nfl.util.StringUtil;

public class SeasonDao extends BaseDao {

	private static SeasonDao instance = new SeasonDao();

    @Override
    public String getUnderlyingTableName() {
        return "SEASON";
    }

    public static SeasonDao getInstance() {
        return instance ;
    }

    public Season findByName(String name) {
        String findByNameQuery = getFindByNameQuery(name);
        return buildSeason(findByNameQuery);
    }

    private Season buildSeason(String sql) {
        Season season = null;
        ResultSet rs = super.findByQuery(sql);
        
        try {
            if(rs.next()){
            	season = SeasonHelper.createNewSeason(Long.valueOf(rs.getLong("ID")), rs.getString("NAME"));
            }
            rs.close();
        } catch (SQLException e) {
            throw new ValidationException(e.getMessage() + " in buildSeason()");
        } finally {
            rs = null;            
        }
        return season;
    }

    public Season create(Season season) {
        String sql = "INSERT INTO " + getUnderlyingTableName() + " (NAME) VALUES (" + StringUtil.addSingleQuotes(season.getName()) + ");";
        return findById(super.create(sql));
    }

    public Season findById(Long id) {
        String findByIdQuery = getFindByIdQuery(id);
        return buildSeason(findByIdQuery);
    }

}
